from django.contrib.auth import authenticate, login, logout

from django.views import View
import json
import re
from django.http import JsonResponse
from django_redis import get_redis_connection

from aijia.utils.qiniuyun.qiniu_storage import storage
from aijia.utils.view import LoginRequiredMixin
from users.models import User


class UsersView(View):
    '''注册'''


class UsersView(View, LoginRequiredMixin):

    def post(self, request):
        '''接收参数，保存到数据库'''
        #接收参数
        dic=json.loads(request.body)
        mobile=dic.get('mobile')
        phonecode_client=dic.get('phonecode')
        password=dic.get('password')

        #整体检验
        if not all([mobile, phonecode_client, password]):
            return JsonResponse({'errno':'400',
                                 'errmsg':'缺少必传参数'})
        #mobile检验
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return JsonResponse({'errno': '400',
                                 'errmsg': 'mobile有误'})
        #password检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'errno': 400,
                                 'errmsg': 'password格式有误'})


        # 8.phonecode检验 (链接redis数据库)
        redis_conn = get_redis_connection('verify_code')

        # 9.从redis中取值
        phonecode_server = redis_conn.get('sms_%s' % mobile)

        # 10.判断该值是否存在
        if not phonecode_server:
            return JsonResponse({'code': 400,
                                 'errmsg': '短信验证码过期'})

        # 11.把redis中取得值和前端发的值对比
        if phonecode_client != phonecode_server.decode():
            return JsonResponse({'errno': 400,
                                 'errmsg': '验证码有误'})

        # 12.保存到数据库 (username password mobile)
        try:
            user = User.objects.create_user(password=password,
                                            mobile=mobile,
                                            username=mobile)
        except Exception as e:
            return JsonResponse({'errno': 400,
                                 'errmsg': '保存到数据库出错'})

        # 生成响应对象
        response = JsonResponse({'code': 0,
                                 'errmsg': 'ok'})

        # 在响应对象中设置用户名信息.
        # 将用户名写入到 cookie，有效期 14 天
        response.set_cookie('username',
                            user.username,
                            max_age=3600 * 24 * 14)

        # 返回响应结果
        return response



class SessionView(View):
    # 实现登录
    def post (self , request):
        #接收参数
        dic=json.loads(request.body)
        mobile=dic.get('mobile')
        password=dic.get('password')
        #检验参数
        if not all([mobile, password]):
            return JsonResponse({'errno': 400,
                                 'errmsg': '缺少必传参数'})

        # 3.验证是否能够登录
        user = authenticate(mobile=mobile,
                            password=password,
                            username=mobile)

        # 判断是否为空,如果为空,返回
        if user is None:
            return JsonResponse({'errno': 400,
                                 'errmsg': '用户名或者密码错误'})

        login(request, user)

        # 生成响应对象
        response = JsonResponse({'errno': 0,
                                 'errmsg': 'ok'})

        # 在响应对象中设置用户名信息.
        # 将用户名写入到 cookie，有效期 14 天
        response.set_cookie('username',
                            user.username,
                            max_age=3600 * 24 * 14)
        # 返回响应结果
        return response


    def get(self, request):
        data = {
            'name': request.user.username,
            'user_id': request.user.mobile,
        }
        return JsonResponse({'errno':0,
                             'errmsg':'已登录',
                             'data':data
                             })

    def delete(self, request):
        """实现退出登录逻辑"""

        # 清理 session
        logout(request)

        # 创建 response 对象.
        response = JsonResponse({'errno': 0,
                                 'errmsg': '已登出'})

        # 调用对象的 delete_cookie 方法, 清除cookie
        response.delete_cookie('username')

        # 返回响应
        return response

class UserInfoView(View):
    """用户中心"""

    def get(self, request):
        """提供个人信息界面"""

        # 获取界面需要的数据,进行拼接
        data = {
            'name': request.user.username,
            'mobile': request.user.mobile,
        }

        # 返回响应
        return JsonResponse({'errno':0,
                             'errmsg':'ok',
                             'data':data})


class Upload_user_pic(View, LoginRequiredMixin):

     def post(self, request):
        # 接受参数
        image_file = request.FILES.get('avatar')
        if not image_file:
            return JsonResponse({
                                'code':400,
                                'errmsg':'为上传图片'
           })
        image_data = image_file.read()
        try:
            file_name = storage(image_data)
        except Exception as e:
            return JsonResponse({
                "code":400,
                'errmsg':'上传失败'
            })

        try:
            User.objects.filter(id=request.user.id).update(avatar=file_name)
        except Exception as e:
            return JsonResponse({
                "code":400,
                'errmsg':'保存失败'
            })
        avatar_url = 'http://qetyapafg.bkt.clouddn.com/'+file_name
        return JsonResponse({
            'data':{'avatar':avatar_url},
            'errno':0,
            'errmsg':'头像上传成功'
        })



        pass

class Change_user_name(View):

    def put(self,request):
        dict = json.loads(request.body)
        name = dict.get('name')
        if not name:
            return JsonResponse({'code': 400,
                                 'errmsg': '用户名不能为空'})
        try:
            #request.user.set_user(name)
            # user = User.objects.get(request.user)
            # user.username=name
            User.objects.filter(username=request.user.username).update(username=name)
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '修改用户名失败'})
        logout(request)

        response = JsonResponse({'errno': 0,
                                 'errmsg': '修改成功'})

        response.delete_cookie('username')

        # # 响应密码修改结果：重定向到登录界面
        return response
